package com.meida.boot.handler;

import com.meida.common.constants.CommonConstants;
import com.meida.common.mybatis.entity.EntityMap;
import com.meida.common.mybatis.interceptor.PageInterceptor;
import com.meida.common.mybatis.model.ListModel;
import com.meida.common.mybatis.model.PageParams;
import com.meida.common.mybatis.model.ResultBody;
import com.meida.common.mybatis.query.CriteriaQuery;
import com.meida.common.security.OpenHelper;
import com.meida.common.utils.DateUtils;
import com.meida.module.marketing.client.entity.MkgCoupon;
import com.meida.module.marketing.provider.service.CouponUserService;
import com.meida.module.product.client.entity.ProdShop;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.smartcardio.CommandAPDU;
import java.util.List;

/**
 * 商家优惠券列表
 *
 * @author zyf
 */
@Component("shopCouponListHandler")
public class ShopCouponListHandler implements PageInterceptor<MkgCoupon> {

    @Autowired
    private CouponUserService couponUserService;


    @Override
    public ResultBody validate(CriteriaQuery cq, EntityMap params) {
        return ResultBody.ok();
    }

    @Override
    public void prepare(CriteriaQuery cq, PageParams pageParams, EntityMap params) {
        Long shopId = params.getLong("shopId");
        cq.ge("expiryEndTime", DateUtils.getDateTime());
        cq.eq(true, "state", CommonConstants.ENABLED);
        cq.eq(true, "shopId", shopId);
    }

    @Override
    public void complete(CriteriaQuery<MkgCoupon> cq, List<EntityMap> result, EntityMap extra) {
        Long userId = OpenHelper.getUserId();
        for (EntityMap entityMap : result) {
            Long couponId = entityMap.getLong("couponId");
            Integer num = couponUserService.countByCouponAndUserId(userId, couponId);
            Integer receiveNum = entityMap.getInt("receiveNum", 0);
            Integer receiveState;
            if (num < receiveNum && receiveNum > 0) {
                //可领取
                receiveState = 1;
            } else {
                //不可领取
                receiveState = 0;
            }
            entityMap.put("receiveState", receiveState);
        }
    }

}
